package com.example.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.software.dto.LoginDTO;
import com.example.software.entity.User;
import com.example.software.mapper.UserMapper;
import com.example.software.service.AuthService;
import com.example.software.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl extends ServiceImpl<UserMapper, User> implements AuthService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Override
    public String login(LoginDTO loginDTO) {
        // 查询用户
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, loginDTO.getUsername())
        );
        
        // 验证用户是否存在
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成token
        return jwtTokenUtil.generateToken(user.getId(), user.getUsername(), user.getUserType());
    }
    
    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, user.getUsername())
        );
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 保存用户
        return save(user);
    }
    
    @Override
public boolean resetPassword(String username, String newPassword) {
    // 查询用户
    User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, username)
    );
    
    if (user == null) {
        throw new RuntimeException("用户不存在");
    }
    
    // 加密新密码
    user.setPassword(passwordEncoder.encode(newPassword));
    
    // 更新用户
    return updateById(user);
}
} 